﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;

namespace JoinBoxCurrency
{
    public class CadProcess
    {
        public enum RunCadVer
        {
            Minimum,
            Maximum,
            All,
        }
        public Process[] Record { get; private set; }

        const string _acad = "acad";
        const string _acadexe = "\\acad.exe";
        string _workingDirectory;

        /// <summary>
        /// 获取已经打开的cad程序
        /// </summary>
        public void GetExisting()
        {
            Record = Process.GetProcessesByName(_acad);
        }

        /// <summary>
        /// 构造函数,初始化
        /// </summary>
        public CadProcess()
        {
            Record = new Process[0];
            _workingDirectory = Environment.GetEnvironmentVariable("TEMP");
        }

        /// <summary>
        /// 启动cad程序
        /// </summary>
        /// <param name="runCadVer">启动什么版本</param>
        public void Run(RunCadVer runCadVer = RunCadVer.Minimum)
        {
            string progID = "AutoCAD.Application.";
            string exePath = null;

            //获取本机cad路径
            var regedit = new AcadDirs();
            if (regedit.Dirs.Count == 0)
            {
                return;
            }

            //按照版本排序
            var ob = regedit.Dirs.OrderBy(cad => cad.Version).ToList();
             
            switch (runCadVer)
            {
                case RunCadVer.Minimum:
                    {
                        progID += ob[0].Version;
                        exePath = ob[0].Location + _acadexe;
                        Run(progID, exePath);
                    }
                    break;
                case RunCadVer.Maximum:
                    {
                        progID += ob[ob.Count - 1].Version;
                        exePath = ob[ob.Count - 1].Location + _acadexe;
                        Run(progID, exePath);
                    }
                    break;
                case RunCadVer.All:
                    {
                        foreach (var reg in regedit.Dirs)
                        {
                            Run(progID + reg.Version, reg.Location + _acadexe);
                        }
                    }
                    break;
            }
        }


        private void Run(string progID, string exePath)
        {
            //处理GetActiveObject在电脑睡眠之后获取就会失败.所以要ProcessStartInfo
            //https://blog.csdn.net/yuandingmao/article/details/5558763?_t_t_t=0.8027849649079144
            //string progID = "AutoCAD.Application.17.1";
            //string exePath = @"C:\Program Files (x86)\AutoCAD 2008\acad.exe";

            object acApp = null;
            try
            {
                acApp = Marshal.GetActiveObject(progID);
            }
            catch { }
            if (acApp == null)
            {
                try
                {
                    // var psi = new ProcessStartInfo(exePath, "/p myprofile");//使用cad配置,myprofile是配置名称,默认就不写
                    var psi = new ProcessStartInfo(exePath, "/nologo")
                    {
                        WorkingDirectory = _workingDirectory//这里什么路径都可以的
                    };
                    Process pr = Process.Start(psi);
                    pr.WaitForInputIdle();
                    while (acApp == null)
                    {
                        try
                        {
                            acApp = Marshal.GetActiveObject(progID);
                        }
                        catch
                        {
                            // Application.DoEvents();
                        }
                        Thread.Sleep(500);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("无法创建或附加到AutoCAD对象: " + ex.Message);
                }
            }
            if (acApp != null)
            {
                GetExisting();
            }
        }
    }
}
